// src/api/service/ProductADService.tsx
import graphqlClient from '../../api/GraphqlConfig';
import {
    PRODUCT_AD_LIST,
    PRODUCT_AD_CREATE,
    PRODUCT_AD_DELETE
} from '../gql/ProductADGQL';

// 广告数据类型定义
export interface ProductAd {
    id: string;
    coverAddr: string;
    productId: string;
    createTime: string;
    updateTime: string;
}

export interface ProductAdListResponse {
    advertisingList: ProductAd[];
}

export interface CreateProductAdInput {
    coverAddr?: string;
    productId: string;
}

class ProductADService {
    /**
     * 获取广告列表
     * @returns 广告列表响应
     */
    async getProductAdList(): Promise<ProductAdListResponse> {
        try {
            const result = await graphqlClient.query<{ productAd: ProductAdListResponse }>({
                query: PRODUCT_AD_LIST
            });
            return result.data!.productAd;
        } catch (error) {
            console.error('获取广告列表失败:', error);
            throw error;
        }
    }

    /**
     * 创建广告
     * @param input 广告信息
     * @returns 创建的广告
     */
    async createProductAd(input: CreateProductAdInput): Promise<ProductAd> {
        try {
            const result = await graphqlClient.mutate<{ productAd: { createAdvertising: ProductAd } }>({
                mutation: PRODUCT_AD_CREATE,
                variables: {
                    coverAddr: input.coverAddr,
                    productId: input.productId
                }
            });
            return result.data!.productAd.createAdvertising;
        } catch (error) {
            console.error('创建广告失败:', error);
            throw error;
        }
    }

    /**
     * 删除广告
     * @param id 广告ID
     * @returns 删除结果
     */
    async deleteProductAd(id: string): Promise<boolean> {
        try {
            const result = await graphqlClient.mutate<{ productAd: { deleteAdvertising: boolean } }>({
                mutation: PRODUCT_AD_DELETE,
                variables: { id }
            });
            return result.data!.productAd.deleteAdvertising;
        } catch (error) {
            console.error('删除广告失败:', error);
            throw error;
        }
    }
}

// 创建并导出 ProductADService 实例
export const productADService = new ProductADService();
